package com.lifeng.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by lifeng on 2019/8/9.
 */
@Controller
public class LoginController {
    private static final Logger log = LoggerFactory.getLogger(LoginController.class);
    @Resource
    private AuthenticationManager myAuthenticationManager;
    @Resource
    private SessionRegistry sessionRegistry;

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/tologin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username,String password,HttpServletRequest request){
        //构造用户名和名
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = null;
        try {
            //使用SpringSecurity拦截登陆请求 进行认证和授权
            authenticate = myAuthenticationManager.authenticate(usernamePasswordAuthenticationToken);
        }catch (Exception e){
            log.error("登陆请求 进行认证失败",e);
            throw e;
        }
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        //校验通过，注册session
        sessionRegistry.registerNewSession(request.getSession().getId(),authenticate.getPrincipal());
        return "redirect:index";
    }

    /** 可以不写此方法 security默认提供退出方法 /logout*/
    @RequestMapping("/exit")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null){
            new SecurityContextLogoutHandler().logout(request, response, auth);
            if(auth.getPrincipal()!=null){
                List<SessionInformation> allSessions = sessionRegistry.getAllSessions(auth.getPrincipal(), false);
                if (allSessions != null) {
                    for (SessionInformation sessionInformation : allSessions) {
                        sessionInformation.expireNow();
                        sessionRegistry.removeSessionInformation(sessionInformation.getSessionId());
                    }
                }
            }
        }
        return null;
    }
}
